package com.cya.lotterysystem.controller;

import com.cya.lotterysystem.common.pojo.CommonResult;
import com.cya.lotterysystem.common.utils.JacksonUtil;
import com.cya.lotterysystem.controller.param.DrawPrizeParam;
import com.cya.lotterysystem.controller.param.ShowWinningRecordsParam;
import com.cya.lotterysystem.controller.reslut.WinningRecordsResult;
import com.cya.lotterysystem.service.DrawPrizeService;
import com.cya.lotterysystem.service.dto.WinnerResultDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/11/6 22:19
 * @description：
 * @modified By：
 * @version:
 */
@RestController
@Slf4j
public class DrawPrizeController {

    @Autowired
    private DrawPrizeService drawPrizeService;

    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(@Valid @RequestBody DrawPrizeParam param){

        log.info("drawPrize DrawPrizeParam:{}",param);
        //service
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }

    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordsResult>> showWinningRecords(@Validated @RequestBody ShowWinningRecordsParam param) throws JsonProcessingException {

        log.info("showWinningRecords ShowWinningRecordsParam:{}", JacksonUtil.writeValueAsString(param));
        List<WinnerResultDTO> winnerResultDTOList=drawPrizeService.getRecords(param);

        return CommonResult.success(converToWinnerRecordsResult(winnerResultDTOList));

    }

    private List<WinningRecordsResult> converToWinnerRecordsResult(List<WinnerResultDTO> winnerResultDTOList) {

        if (CollectionUtils.isEmpty(winnerResultDTOList)){
            return Arrays.asList();
        }
        return winnerResultDTOList.stream()
                .map(WinnerResultDTO->{
                    WinningRecordsResult result=new WinningRecordsResult();
                    result.setWinnerId(WinnerResultDTO.getWinnerId());
                    result.setWinnerName(WinnerResultDTO.getWinnerName());
                    result.setPrizeName(WinnerResultDTO.getPrizeName());
                    result.setPrizeTier(WinnerResultDTO.getPrizeTier().getMessage());
                    result.setWinningTime(WinnerResultDTO.getWinningTime());
                return result;

                }).collect(Collectors.toList());
    }

}